<template>
    <div>
        <p>
            <button class="btn btn-white btn-default btn-round" @click="refresh()">
                <i class="ace-icon fa fa-refresh red"></i>
                刷新
            </button>
            &nbsp;
            <button class="btn btn-white btn-success btn-round" @click="openAddModal()">
                <i class="ace-icon fa fa-edit blue"></i>
                新增
            </button>
        </p>

        <table id="simple-table" class="table  table-bordered table-hover">
            <thead>
            <tr>
                <th class="center">ID</th>
                <th class="center">角色</th>
                <th class="center">描述</th>
                <th class="center">操作</th>
            </tr>
            </thead>

            <tbody>
            <tr v-for="role in roles">
                <td class="center">{{role.id}}</td>
                <td class="center">{{role.name}}</td>
                <td class="center">{{role.desc}}</td>
                <td class="center">
                    <div class=" btn-group">
                        <button class="btn btn-white btn-xs btn-default btn-round" @click="openAssignResourceModal(role.id)">
                            <i class="ace-icon fa fa-list bigger-120"></i>
                        </button>
                        <button class="btn btn-white btn-xs btn-default btn-round" @click="openEditModal(role.id)">
                            <i class="ace-icon fa fa-edit bigger-120"></i>
                        </button>

                        <button class="btn btn-white btn-xs btn-danger btn-round" @click="deleteById(role.id)">
                            <i class="ace-icon fa fa-trash-o bigger-120"></i>
                        </button>
                    </div>

                </td>
            </tr>
            <tr v-if="roles.length === 0">
                <td colspan="4" class="center">暂无数据</td>
            </tr>
            </tbody>
        </table>
        <!-- 分页组件 -->
        <pagination ref="pagination" v-bind:list="list"></pagination>

        <!-- 模态框 -->
        <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content" style="border-color: #aa160e;background-color: lightblue">
                    <div class="modal-header">
                        <button type="button" class="close blue" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title grey bolder" id="myModalLabel">{{modalTitle}}</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" role="form">
                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right"> 角色 </label>
                                <div class="col-sm-9">
                                    <input v-model="role.name" type="text" placeholder="角色" class="col-xs-10 col-sm-5"/>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right"> 描述</label>
                                <div class="col-sm-9">
                                    <input v-model="role.desc" type="text" placeholder="描述" class="col-xs-10 col-sm-5"/>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default btn-round"
                                data-dismiss="modal">
                            关闭
                        </button>
                        <button @click="save()" type="button" class="btn btn-primary btn-round"
                                >
                            保存
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 角色资源关联配置 -->
        <div id="resource-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content" style="border-color: #aa160e;background-color: lightblue">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">角色资源关联配置</h4>
                    </div>
                    <div class="modal-body">
                        <ul id="tree" class="ztree"></ul>
                    </div>
                    <div class="modal-footer">
						<button type="button" class="btn btn-default btn-round"
								data-dismiss="modal">
							关闭
						</button>
						<button @click="saveResource()"  type="button" class="btn btn-primary btn-round">
							保存
						</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </div>

</template>

<script>
    import Pagination from "../../components/pagination.vue"

    export default {
        name: "role",
        components: {
            Pagination
        },
        data: function () {
            return {
                roles: [],
                role: {},
                modalTitleArr: {
                    insert: "新增角色",
                    update: "修改角色"
                },
                modalTitle: "",
				zTree: {},
				resources:[],
				roleId:""

            }
        },
        mounted: function () {
            // this.$parent.activeSidebar("system-role-sidebar")
            let _this = this;
            _this.list();
        },
        methods: {
			/**
			 * 资源模态框点击【保存】
			 */
			saveResource() {
				let _this = this;
				let resources = _this.zTree.getCheckedNodes();
				// 保存时，只需要保存资源id，所以使用id数组进行参数传递
				let resourceIds = [];
				for (let i = 0; i < resources.length; i++) {
					resourceIds.push(resources[i].id);
				}
				_this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roleResource/saveBatch', {
					roleId: _this.roleId,
					resourceIds: resourceIds
				}).then((response)=>{
					let resp = response.data;
					if (resp.success) {
						Toast.success(resp.message);
					} else {
						Toast.error(resp.message);
					}
					$("#resource-modal").modal("hide");
				});
			},
			/**
			 * 加载角色资源关联记录
			 */
			listRoleResource() {
				let _this = this;
				_this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/resource/findResourcesByRoleId/' + _this.roleId).then((response)=>{
					let resp = response.data;
					let resources = resp.data;
					// 勾选查询到的资源：先把树的所有节点清空勾选，再勾选查询到的节点
					_this.zTree.checkAllNodes(false);
					for (let i = 0; i < resources.length; i++) {
						let node = _this.zTree.getNodeByParam("id", resources[i]);
						if (node) {
							_this.zTree.checkNode(node, true);
						}
					}
				});
			},
			/**
			 * 初始资源树
			 */
			initTree() {
				let _this = this;
				let setting = {
					check: {
						enable: true
					},
					data: {
						simpleData: {
							idKey: "id",
							pIdKey: "parent",
							rootPId: "0",
							enable: true
						}
					}
				};
				_this.zTree = $.fn.zTree.init($("#tree"), setting, _this.resources);
				_this.zTree.expandAll(true);
			},
        	/*获取所有的资源*/
			getAllResources() {
				let _this = this;
				_this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/resource/findTreeResources').then((response) => {
					_this.resources = response.data.data;
					//初始化树
					_this.initTree();
					_this.listRoleResource();
				});
			},
        	/*打开资源分配模态框*/
			openAssignResourceModal(roleId) {
				let _this = this;
				_this.roleId = roleId;
				_this.getAllResources();
				$("#resource-modal").modal({backdrop: 'static'});
				$("#resource-modal").modal("show");
			},
            /* 打开新增模态框 */
            openAddModal() {
                let _this = this;
                _this.clearRole();
                _this.modalTitle = _this.modalTitleArr.insert;
                $("#myModal1").modal({backdrop: 'static'});
                $("#myModal1").modal("show");

            },
            /*打开编辑模态框*/
            openEditModal(id) {
                let _this = this;
                _this.clearRole();
                _this.modalTitle = _this.modalTitleArr.update;
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/role/findById/' + id).then((response) => {
                    _this.role = response.data.data;
                });
                $("#myModal1").modal({backdrop: 'static'});
                $("#myModal1").modal("show");
            },
            refresh() {
                let _this = this;
                Loading.show();
                _this.list(_this.$refs.pagination.page);
                Loading.hide();
            },
            /* 查找角色 */
            list(page = 1) {
                let _this = this;
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/list', {
                    page: page,
                    size: _this.$refs.pagination.size
                }).then((response) => {
                    _this.roles = response.data.data.list;
                    _this.$refs.pagination.render(page, response.data.data.total);
                })
            },
            /*保存角色信息到后台*/
            save() {
                let _this = this;
                if (!_this.role.id) {
                    /*不存在id为新增*/
                    _this.insert();
                } else {
                    /*存在id为修改*/
                    _this.update();
                }
            },
            /*新增角色*/
            insert() {
                let _this = this;
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/save', _this.role).then((response) => {
                    console.log(response);
                    if (response.data.success) {
                        _this.list(_this.$refs.pagination.page);
                        Toast.success(response.data.message);
                    } else {
                        Toast.error(response.data.message);
                    }
                    $("#myModal1").modal("hide");
                });
            },
            /*修改角色*/
            update() {
                let _this = this;
                _this.$ajax.put(process.env.VUE_APP_SERVER + '/system/admin/role/update', _this.role).then((response) => {
                    if (response.data.success) {
                        _this.list(_this.$refs.pagination.page);
                        Toast.success(response.data.message);
                    } else {
                        Toast.error(response.data.message);
                    }
                    $("#myModal1").modal("hide");
                })
            },
            /*删除角色*/
            deleteById(id) {
                let _this = this;
                /*删除提示框*/
                Confirm.show("", () => {
                    _this.$ajax.delete(process.env.VUE_APP_SERVER + '/system/admin/role/deleteById/' + id).then((response) => {
                        if (response.data.success) {
                            _this.list(_this.$refs.pagination.page);
                            Toast.success(response.data.message);
                        } else {
                            Toast.error(response.data.message);
                        }
                        $("#myModal1").modal("hide");
                    })
                });
            },
            /*清空模态框的数据*/
            clearRole() {
                let _this = this;
                _this.role = {};
                _this.modalTitle = "";
            }
        }
    }
</script>
